using System;
using System.Runtime.InteropServices;
using System.Security.Permissions;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Security;
using MS.InformationManagement.Support;
using MS.InformationManagement.Support.Constants;
using System.Collections.Generic;
using System.Linq;
using Microsoft.SharePoint.Taxonomy;
using MS.InformationManagement.DAL.DocumentCenter;

namespace MS.InformationManagement.Documents.ObjectDef.Features.Roles
{
    /// <summary>
    /// This class handles events raised during feature activation, deactivation, installation, uninstallation, and upgrade.
    /// </summary>
    /// <remarks>
    /// The GUID attached to this class may be used during packaging and should not be modified.
    /// </remarks>

    [Guid("15c2fddd-76b6-4d09-a6cb-8a78812f0ce0")]
    public class RolesEventReceiver : SPFeatureReceiver
    {
        // Uncomment the method below to handle the event raised after a feature has been activated.

        public override void FeatureActivated(SPFeatureReceiverProperties properties)
        {
            SPSite currentSite = properties.Feature.Parent as SPSite;
            using (SPWeb currentWeb = currentSite.OpenWeb())
            {
                LookUpFieldCreation(CustomSiteColumns.FIELD_DISPLAY_ROLE_LOOKUP, CustomSiteColumns.FIELD_INTERNAL_NAME_ROLE_LOOKUP, GlobalConstants.LIST_PERFILES_ROL, GlobalConstants.LIST_ROLES, GlobalConstants.CTTN_PERFILES_ROL, "MS Information Management", true, true, currentWeb, true);
                //LoadInitialData(currentWeb);
            }
        }
        public static void LookUpFieldCreation(string fieldDisplayName, string staticName, string sourceList, string targetList, string contentType, string fieldGroup, bool multiValue, bool updateChild, SPWeb currentWeb, bool required)
        {

            SPFieldLookup lookup = null;

            //Removing field if exists

            Dictionary<string, string> currentListCollection = new Dictionary<string, string>();
            currentListCollection.Add(sourceList, contentType);
            removeLinkField(fieldDisplayName, staticName, currentWeb, currentListCollection);
            currentWeb.Fields.AddLookup(fieldDisplayName, currentWeb.Lists[targetList].ID, currentWeb.ID, false);
            currentWeb.Update();

            lookup = (SPFieldLookup)currentWeb.Fields[fieldDisplayName];
            lookup.AllowMultipleValues = multiValue;
            lookup.Required = required;
            lookup.LookupField = "Role_Name";
            lookup.Group = fieldGroup;
            lookup.StaticName = staticName;
            lookup.Update();

            //Adding to site content type

            SPContentType siteCt = currentWeb.ContentTypes[contentType];
            siteCt.FieldLinks.Add(new SPFieldLink(lookup));
            if (updateChild)
                siteCt.Update(true);
            else
                siteCt.Update();


            currentWeb.Update();

        }

        public static void removeLinkField(string fieldDisplayName, string fieldStaticName, SPWeb currentWeb, Dictionary<string, string> lists)
        {

            if (FieldCreationValidation(fieldDisplayName, currentWeb))
            {

                //Deleting from lists

                foreach (KeyValuePair<string, string> list in lists)
                {
                    SPFieldLink field = (from SPFieldLink fieldLink in currentWeb.Lists[list.Key].ContentTypes[list.Value].FieldLinks
                                         where fieldLink.Name.Equals(fieldStaticName)
                                         select fieldLink).SingleOrDefault();
                    if (field != null)
                    {
                        currentWeb.Lists[list.Key].ContentTypes[list.Value].FieldLinks.Delete(field.Id);
                        currentWeb.Lists[list.Key].ContentTypes[list.Value].Update();
                        currentWeb.Lists[list.Key].Update();
                    }

                }

                //Deleting from site 
                if (currentWeb.Fields.ContainsFieldWithStaticName(fieldStaticName))
                    currentWeb.Fields.Delete(fieldDisplayName);

                currentWeb.Update();

            }

        }

        public static bool FieldCreationValidation(string fieldDisplayName, SPWeb currentWeb)
        {

            //Removing from web

            var Countryfield = (from f in currentWeb.Fields.Cast<SPField>()
                                where f.Title.Equals(fieldDisplayName)
                                select f);

            if (Countryfield.Count() > 0)
                return true;
            else
                return false;

        }

        public static void LoadInitialData(SPWeb currentWeb)
        {

            SPList perfiles = currentWeb.Lists[GlobalConstants.LIST_PERFILES_ROL];
            SPListItem item = perfiles.Items.Add();
            item[SPBuiltInFieldId.Title] = "RADICADOR";
            item[CustomSiteColumns.FIELD_INTERNAL_PERFIL] = "RADICADOR";
            item.Update();

        }


    }
}
